/**
 * @create 2022-11-06
 * @desc index
 */

import { FC, createContext, useContext } from 'react';
import { useRequest } from 'ahooks';
import { Result } from 'ahooks/lib/useRequest/src/types';
import { useProTableStore } from './store';
import { FetcherType } from '../types/pro-table';

type RequestState<T = any, Q extends any[] = any[]> = Result<T, Q>;

interface FetcherProps {
  fetcher?: FetcherType;
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const DataContext = createContext<RequestState>({} as any);

// 改成 context
export const DataContextProvider: FC<FetcherProps> = ({ fetcher, children }) => {
  const tableState = useProTableStore();

  const requestResult = useRequest(
    () => {
      if (fetcher) {
        return fetcher({
          pagination: tableState.pagination,
          ...tableState.params,
        });
      }

      return Promise.resolve(undefined);
    },
    {
      manual: false,
      refreshDeps: [fetcher, tableState.pagination, tableState.params],
    },
  );

  return <DataContext.Provider value={requestResult}>{children}</DataContext.Provider>;
};

export const useDataContext = <T extends Record<string, any> = any, Q extends any[] = any[]>() => {
  const request = useContext(DataContext);

  return request as RequestState<T, Q>;
};
